package com.gxa.p2p.controller;

import com.gxa.p2p.common.JsonResult;
import com.gxa.p2p.common.enum1.ExceptionCode;
import com.gxa.p2p.common.exception.MyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Member;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.jar.JarEntry;

/**
 * @author R
 * @data 2021-10-21 15:21
 */
@RestController
//本质上就是一个aop的通知，专门用于加强异常出现的时候的抛出通知
@ControllerAdvice
public class ExceptionController {

    /**
     * 当有异常发生，抛出通知介入到目标操作
     * 并把异常对象注入到参数Exception中
     */
    @ExceptionHandler(Throwable.class)
    public Map handler(Exception e, HttpServletRequest request) throws IOException {
        //具体操作和三阶段一致：自定义异常返给前端，系统异常生成日志（log4j）
        if (e instanceof MyException){
            JsonResult jsonResult = new JsonResult();
            jsonResult.setCode(((MyException) e).getExceptionCode().getCode());
            jsonResult.setMsg(e.getMessage());
            return jsonResult.getDataMap();
        }else {
//系统异常 Exception(RuntimeException/检查异常)
            //处理：记录日志，追加
            //文件的位置确定：1.通过上下文对象获取程序在服务器中的根目录，2.d:/log/error2021-09-15.log
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String realPath = request.getSession().getServletContext().getRealPath("/");
            System.out.println(realPath);
            File file = new File(realPath + "error" + format + ".log.txt");
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
            OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, "UTF8");
            if (!file.exists()) {
                file.createNewFile();
            }
            // FileWriter writer = new FileWriter(file,true);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("----------------------------------------").append("\n");
            stringBuilder.append("异常类型：").append(e.toString()).append("\n");
            stringBuilder.append("异常原因：").append(e.getMessage()).append("\n").append("异常轨迹：");
            for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                stringBuilder.append(stackTraceElement.toString()).append("\n");
            }
            stringBuilder.append("----------------------------------------").append("\n");
            writer.write(stringBuilder.toString());
            writer.flush();
            writer.close();
            JsonResult jsonResult = new JsonResult();
            jsonResult.setCode(ExceptionCode.SERVER_FAILED.getCode());
            jsonResult.setMsg(ExceptionCode.SERVER_FAILED.getMessage());
            return jsonResult.getDataMap();
        }
    }
}
